package org.pada.client.dto;

import java.util.*;
import java.util.function.Function;

/**
 * @author shen.peng
 * @since 2024/10/12
 */
public class CursorResp<T, C> extends Resp {
    private static final long serialVersionUID = 1L;

    private C cursor;

    private Collection<T> data;


    public void setCursor(C cursor) {
        this.cursor = cursor;
    }

    public C getCursor() {
        return cursor;
    }

    public List<T> getData() {
        return null == data ? Collections.emptyList() : new ArrayList<>(data);
    }

    public void setData(Collection<T> data) {
        this.data = data;
    }

    public boolean isEmpty() {
        return data == null || data.size() == 0;
    }

    public boolean isNotEmpty() {
        return !isEmpty();
    }

    public static CursorResp buildSuccess() {
        CursorResp resp = new CursorResp();
        resp.setSuccess(true);
        return resp;
    }

    public static CursorResp buildFailure(String errCode, String errMessage) {
        CursorResp resp = new CursorResp();
        resp.setSuccess(false);
        resp.setErrCode(errCode);
        resp.setErrMessage(errMessage);
        return resp;
    }

    public static <T, C> CursorResp<T, C> ofCursor(List<T> data, C cursor) {
        CursorResp<T, C> resp = new CursorResp<>();
        resp.setSuccess(true);
        resp.setData(data);
        resp.setCursor(cursor);
        return resp;
    }

    public static <T, C> CursorResp<T, C> ofCursor(List<T> data, Function<T, C> idf) {
        CursorResp<T, C> resp = new CursorResp<>();
        resp.setSuccess(true);
        resp.setData(data);
        resp.setCursor(getLast(data).map(idf).orElse(null));
        return resp;
    }

    private static <T> Optional<T> getLast(List<T> data) {
        if (data == null || data.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(data.get(data.size() - 1));
    }
}
